package com.wang.auto;

import com.sun.scenario.effect.impl.sw.java.JSWBlend_SRC_OUTPeer;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.wang.conf.AppConf;
import com.wang.conf.AppData;
import com.wang.packpojo.ConMsg;
import com.wang.packpojo.NowCommandPack;
import com.wang.packpojo.Param;
import com.wang.packpojo.SocketMsg;
import com.wang.pojo.DevC1dtParamConf;
import com.wang.pojo.DevC1dtParamConfData;
import com.wang.pojo.DevMdtParamConf;
import com.wang.pojo.Device;
import com.wang.socket.OutBoundHandler;
import com.wang.socket.SocketMap;
import com.wang.util.*;
import com.wang.webSocket.WebOutBoundHander;
import com.wang.webSocket.WebSocketMap;
import com.wang.webSocket.WebSocketUtil;
import io.netty.channel.ChannelHandlerContext;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ExecutorService;

public class AutoSend {


    private ExecutorService executorService = ExecutorServiceUtil.getInstance();

    public void init() {

        //新建一个死循环
        new Thread(() -> {
            while (true) {
                if (SocketMap.mRegPassDeviceMap != null && SocketMap.mRegPassDeviceMap.size() > 0) {
                    //获取当前时间
                    long currentTime = new Date().getTime();


                    for (Map.Entry<String, ConMsg> entry : SocketMap.mRegPassDeviceMap.entrySet()) {

                        String isOpen = entry.getValue().getIsOpen();

                        if (entry.getValue().getTxDataType().equals(AppData.ModbusDataCode) && (!EmptyUtil.isNotNull(isOpen) || isOpen.equals("1"))) {

                            //默认5分钟
                            Integer collectRate = 5;
                            if (entry.getValue().getCollectRate() != null) {
                                collectRate = entry.getValue().getCollectRate();
                            }


                            //取出间隔时间
                            long spaceTime = collectRate * 1000 * 60;



                            long  regTime = entry.getValue().getRegTime(); //注册时间

                            //发送指令时间为空时   并且延迟超过5分钟
                            if ((entry.getValue().getSendCommandTime() == 0 || currentTime - entry.getValue().getSendCommandTime() >= spaceTime) && (currentTime-regTime>=AppConf.delayTime) ) {


                                //更新发送指令时间
                                entry.getValue().setSendCommandTime(new Date().getTime());

                                //创建任务
                                Runnable r = new Runnable() {
                                    @Override
                                    public void run() {
                                        //发送数据
                                        try {
                                            //String 地址位 String 指令
                                            Map<String, DevMdtParamConf> commandMap = entry.getValue().getCommandMap();


                                            //如果指令数量大于1 ，则发数据 建立全局变量 等待全部存储

                                            if (commandMap != null && commandMap.size() > 1) {

                                                for (Map.Entry<String, DevMdtParamConf> entry1 : commandMap.entrySet()) {


                                                    //发送指令
                                                    byte[] commandByte = ModBusUtil.HexString2Bytes(entry1.getKey());


                                                    OutBoundHandler.outData(entry.getValue().getCtx(), commandByte);

                                                    PrintUtil.print("服务端-->设备编码：" + entry.getValue().getDevice().getDevGId() + "：" + entry1.getKey());

                                                    //记录当前发送的指令
                                                    NowCommandPack nowCommandPack = new NowCommandPack();
                                                    nowCommandPack.setCommand(entry1.getKey());
                                                    nowCommandPack.setParamConf(entry1.getValue());
                                                    nowCommandPack.setSendTime(new Date().getTime());

                                                    entry.getValue().setNowCommandPack(nowCommandPack);

                                                    WebSocketUtil.sendTestData(entry.getValue().getDevice().getDevGId(), entry1.getKey());
                                                    boolean flag = true;
                                                    Long sendTime = new Date().getTime();
                                                    while (flag) {
                                                        //如果配置信息中 当前发送的指令为空  或者超过3秒 就跳出循环
                                                        if (entry.getValue() == null || (new Date().getTime() - sendTime) >= AppConf.commandInterval) {
                                                            flag = false;
                                                        }
                                                    }

                                                }
                                            } else if (commandMap != null && commandMap.size() == 1) {
                                                //如果指令数量等于1, 则直接 发送命令 存储数据
                                                String command = "";
                                                DevMdtParamConf devMdtParamConf = null;
                                                for (Map.Entry<String, DevMdtParamConf> entry2 : commandMap.entrySet()) {

                                                    command = entry2.getKey();
                                                    devMdtParamConf = entry2.getValue();
                                                }


                                                //记录当前发送的指令
                                                NowCommandPack nowCommandPack = new NowCommandPack();
                                                nowCommandPack.setCommand(command);
                                                nowCommandPack.setParamConf(devMdtParamConf);
                                                nowCommandPack.setSendTime(new Date().getTime());

                                                entry.getValue().setNowCommandPack(nowCommandPack);


                                                //去除所有的空格
                                                byte[] commandByte = ModBusUtil.HexString2Bytes(command);

                                                OutBoundHandler.outData(entry.getValue().getCtx(), commandByte);
                                                PrintUtil.print("服务端发送指令2-->设备编码：" + entry.getValue().getDevice().getDevGId() + "：" + command);

                                                WebSocketUtil.sendTestData(entry.getValue().getDevice().getDevGId(), command);


                                            }

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                };
                                executorService.execute(r);
                            }
                        }

                    }

                }

                //自定义格式设备
                if(SocketMap.c1RegPassDeviceMap !=null && SocketMap.c1RegPassDeviceMap.size()>0){


                    //获取当前时间
                    long currentTime = new Date().getTime();


                    for (Map.Entry<String, ConMsg> entry : SocketMap.c1RegPassDeviceMap.entrySet()) {

                        String isOpen = entry.getValue().getIsOpen();

                        if (entry.getValue().getTxDataType().equals(AppData.CustomOneCode) && (!EmptyUtil.isNotNull(isOpen) || isOpen.equals("1"))) {



                            //默认5分钟
                            Integer collectRate = 5;
                            if (entry.getValue().getCollectRate() != null) {
                                collectRate = entry.getValue().getCollectRate();
                            }


                            //取出间隔时间
                            long spaceTime = collectRate * 1000 * 60;


                            long  regTime = entry.getValue().getRegTime(); //注册时间

                            //发送指令时间为空时   并且延迟超过2分钟
                            if ((entry.getValue().getSendCommandTime() == 0 || currentTime - entry.getValue().getSendCommandTime() >= spaceTime) && (currentTime-regTime>=AppConf.delayTime) ) {



                                //更新发送指令时间
                                entry.getValue().setSendCommandTime(new Date().getTime());

                                //创建任务
                                Runnable r = new Runnable() {
                                    @Override
                                    public void run() {
                                        //发送数据
                                        try {
                                            //String 地址位 String 指令
                                            Map<String, DevC1dtParamConfData> commandMap = entry.getValue().getCommandMap();



                                            //如果指令数量大于1 ，则发数据 建立全局变量 等待全部存储

                                            if (commandMap != null && commandMap.size() > 1) {



                                                for (Map.Entry<String, DevC1dtParamConfData> entry1 : commandMap.entrySet()) {


                                                    //发送指令
                                                    byte[] commandByte = CustomOneUtil.HexString2Bytes(entry1.getKey());


                                                    OutBoundHandler.outData(entry.getValue().getCtx(), commandByte);

                                                    PrintUtil.print("服务端发送指令1-->设备编码：" + entry.getValue().getDevice().getDevGId() + "：" + entry1.getKey());

                                                    //记录当前发送的指令
                                                    NowCommandPack nowCommandPack = new NowCommandPack();
                                                    nowCommandPack.setCommand(entry1.getKey());
                                                    nowCommandPack.setParamConf(entry1.getValue());
                                                    nowCommandPack.setSendTime(new Date().getTime());

                                                    entry.getValue().setNowCommandPack(nowCommandPack);

                                                    WebSocketUtil.sendTestData(entry.getValue().getDevice().getDevGId(), entry1.getKey());
                                                    boolean flag = true;
                                                    Long sendTime = new Date().getTime();
                                                    while (flag) {
                                                        //如果配置信息中 当前发送的指令为空  或者超过3秒 就跳出循环
                                                        if (entry.getValue() == null || (new Date().getTime() - sendTime) >= AppConf.commandInterval) {
                                                            flag = false;
                                                        }
                                                    }

                                                }
                                            } else if (commandMap != null && commandMap.size() == 1) {
                                                //如果指令数量等于1, 则直接 发送命令 存储数据
                                                String command = "";
                                                DevC1dtParamConfData devC1dtParamConfData = null;
                                                for (Map.Entry<String, DevC1dtParamConfData> entry2 : commandMap.entrySet()) {

                                                    command = entry2.getKey();
                                                    devC1dtParamConfData = entry2.getValue();
                                                }


                                                //记录当前发送的指令
                                                NowCommandPack nowCommandPack = new NowCommandPack();
                                                nowCommandPack.setCommand(command);
                                                nowCommandPack.setParamConf(devC1dtParamConfData);
                                                nowCommandPack.setSendTime(new Date().getTime());

                                                entry.getValue().setNowCommandPack(nowCommandPack);


                                                //去除所有的空格
                                                byte[] commandByte = CustomOneUtil.HexString2Bytes(command);

                                                OutBoundHandler.outData(entry.getValue().getCtx(), commandByte);
                                                PrintUtil.print("服务端发送指令2-->设备编码：" + entry.getValue().getDevice().getDevGId() + "：" + command);

                                                WebSocketUtil.sendTestData(entry.getValue().getDevice().getDevGId(), command);
                                            }

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                };
                                executorService.execute(r);
                            }
                        }

                    }

                }

                //自定义格式设备2
                if(SocketMap.c2RegPassDeviceMap !=null && SocketMap.c2RegPassDeviceMap.size()>0){


                    //获取当前时间
                    long currentTime = new Date().getTime();



                    for (Map.Entry<String, ConMsg> entry : SocketMap.c2RegPassDeviceMap.entrySet()) {



                        String isOpen = entry.getValue().getIsOpen();

                        if (entry.getValue().getTxDataType().equals(AppData.CustomTWOCode) && (!EmptyUtil.isNotNull(isOpen) || isOpen.equals("1"))) {


                            //默认5分钟
                            Integer collectRate = 5;
                            if (entry.getValue().getCollectRate() != null) {
                                collectRate = entry.getValue().getCollectRate();
                            }


                            //取出间隔时间
                            long spaceTime = collectRate * 1000 * 60;


                            long  regTime = entry.getValue().getRegTime(); //注册时间

                            //发送指令时间为空时   并且延迟超过2分钟
                            if ((entry.getValue().getSendCommandTime() == 0 || currentTime - entry.getValue().getSendCommandTime() >= spaceTime) && (currentTime-regTime>=AppConf.delayTime) ) {


                                //更新发送指令时间
                                entry.getValue().setSendCommandTime(new Date().getTime());

                                //创建任务
                                Runnable r = new Runnable() {
                                    @Override
                                    public void run() {
                                        //发送数据
                                        try {
                                            //读取数据的指令
                                            String command = "01 03 00 00 00 09 85 CC";
                                            //去除所有的空格
                                            byte[] commandByte = ModBusUtil.HexString2Bytes(command);

                                            OutBoundHandler.outData(entry.getValue().getCtx(), commandByte);
                                            PrintUtil.print("服务端发送自定义设备2-->设备编码：" + entry.getValue().getDevice().getDevGId() + "：" + command);
                                            WebSocketUtil.sendTestData(entry.getValue().getDevice().getDevGId(), command);

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                };
                                executorService.execute(r);
                            }
                        }

                    }

                }


                //每隔10秒执行一次
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        }).start();


    }


    //获取连接ctx的地址
    public String getRemoteAddress(ChannelHandlerContext ctx) {
        InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = ipSocket.getAddress().getHostAddress();
        Integer port = ipSocket.getPort();
        String ip = clientIp + ":" + port;
        return ip;
    }


}
